package utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;

public class MailUtils {

    private static Properties mailConfig ;

    static {
        try {
            mailConfig=new Properties();
            // 加载邮件配置文件
            mailConfig.load(MailUtils.class.getClassLoader().getResourceAsStream("mail.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 邮件认证器
    private static class MailAuthenticator extends Authenticator {
        private String username;
        private String password;

        public MailAuthenticator(String username, String password) {
            this.username = username;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    }

    /**
     * 发送邮件的方法
     *
     * @param targetAccount       收件人邮箱地址
     * @param subject  邮件主题(邮件标题)
     * @param content  邮件正文
     * @param isHtml   是否为HTML格式邮件
     * @throws MessagingException 邮件发送异常
     */
    public static void sendEmail(String targetAccount,  String subject, String content, boolean isHtml) throws MessagingException {
        // 创建邮件会话
        Properties props = new Properties();
        props.put("mail.smtp.host", mailConfig.getProperty("mail.smtp.host"));
        props.put("mail.smtp.port", mailConfig.getProperty("mail.smtp.port"));
        props.put("mail.smtp.auth", "true");
        // 根据需要开启SSL加密连接
         props.put("mail.smtp.ssl.enable", "true");

        // 创建邮件会话
        Session session = Session.getInstance(props, new MailAuthenticator(mailConfig.getProperty("mail.username"), mailConfig.getProperty("mail.password")));

        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);

        // 设置发件人
        message.setFrom(new InternetAddress(mailConfig.getProperty("mail.username")));

        // 设置收件人
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(targetAccount));

        // 设置邮件主题
        message.setSubject(subject);

        // 设置邮件正文
        if (isHtml) {
            message.setContent(content, "text/html;charset=UTF-8");
        } else {
            message.setText(content, "UTF-8");
        }

        // 发送邮件
        Transport.send(message);
    }

    public static void main(String[] args) throws Exception{
        MailUtils.sendEmail("2771615467@qq.com","hello","test Hello",false);
    }
}


